//
//  BaseDataEngine.m
//  

#import "BaseDataEngine.h"

@interface BaseDataEngine ()

@end

@implementation BaseDataEngine

+ (void)apiForPath:(NSString *)path method:(NSString *)method parameter:(NSMutableDictionary *)parameters onCompleteSuccess:(SuccessAPIBlock)successBlock onCompleteFailur:(FailureAPIBlock)failureBlock withIsForm:(BOOL)isForm{
    
    NSString *fullPath = path;
    if([path hasPrefix:@"http"])
        fullPath =  path;
    else{
        fullPath = [NSString stringWithFormat:@"%@%@", kBaseUrl, path];
    }
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        
    if (isForm) {
        manager.requestSerializer = [AFHTTPRequestSerializer serializer];//form
    } else {
        manager.requestSerializer = [AFJSONRequestSerializer serializer];//json
    }
    
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.requestSerializer.timeoutInterval = 15.0f;
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html",@"image/jpeg",@"text/plain",@"image/png",@"application/octet-stream",@"text/json",@"text/x-vcard",nil];

    fullPath = [fullPath stringByAppendingFormat:@"?meal=%@&warmed=%@&boyfine=%@&inquiring=%@&kitchen=%@&duty=%@&cheerless=%@&blazed=%@",@"ios",@"mmla",@"common",kAppVersion,esString([[UIDevice currentDevice] name]),esString([UIDevice currentDevice].systemVersion),esString([[UIDevice currentDevice] identifierForVendor].UUIDString),esString([[UIDevice currentDevice] identifierForVendor].UUIDString)];
    if (!PMStringIsEmpty(esString([CurrentUser mine].sessionKey))) {
        fullPath = [fullPath stringByAppendingFormat:@"&brightly=%@",esString([CurrentUser mine].sessionKey)];
    }
    
    fullPath = [fullPath stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    DLog(@"========URL=====%@\nparameters=====%@",fullPath,parameters);
    
    if ([[method uppercaseString] isEqualToString:kGetMethod]) {
        
        [manager GET:fullPath parameters:parameters headers:@{} progress:^(NSProgress * _Nonnull downloadProgress) {

            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
                
                if (PMObjectIsEmpty(dic)) {
                    [CreaditUtilsHelper hideLoadMessageBox];
                    return;
                }
                NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
                NSString *jsonStr= [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
//                DLog(@"======Server Get Data(%@)============ %@",path,jsonStr);
                                
                    if (isDictionary(dic) && [dic[@"dim"] integerValue] == kExpireCode) {
                        [CreaditUtilsHelper hideLoadMessageBox];
                        [CreditServerHelper tokenLoseToLogoutController:YES];
                        return;
                    }
            
                if (successBlock) {
                    successBlock(dic);
                }
               

            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                [CreaditUtilsHelper hideLoadMessageBox];
                if (failureBlock) {
                    failureBlock(error);
                }
            }];
 
    } else {
       
        [manager POST:fullPath parameters:parameters headers:@{} progress:^(NSProgress * _Nonnull uploadProgress) {
                    
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                    
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
            
            NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
            NSString *jsonStr= [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
//            DLog(@"======Server Get Data(%@)============ %@",path,jsonStr);
            
                if (isDictionary(dic) && [dic[@"dim"] integerValue] == kExpireCode) {
                    [CreaditUtilsHelper hideLoadMessageBox];
                    [CreditServerHelper tokenLoseToLogoutController:YES];
                    return;
                }
            
            
            if (successBlock) {
                successBlock(dic);
            }
           
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [CreaditUtilsHelper hideLoadMessageBox];
            if (failureBlock) {
                failureBlock(error);
            }
        }];
        
        
    }
}




@end
